/**
 * Skills API Routes
 * 
 * Handles skills management (list, activate, deactivate, etc.)
 */

import { Hono } from 'hono';
import type { ApiResponse } from '@/types';
import { logger } from '@/utils/logger';
import { skillsManager } from '@/skills/skill-manager';
import { builtinSkills } from '@/skills/builtin';

export const skillsRoutes = new Hono();

// Register built-in skills on module load
builtinSkills.forEach(skill => skillsManager.registerSkill(skill));

/**
 * GET /api/skills
 * 
 * List all registered skills
 */
skillsRoutes.get('/', (c) => {
  const allSkills = skillsManager.getAllSkills().map(skill => ({
    id: skill.id,
    name: skill.name,
    description: skill.description,
    category: skill.category,
    version: skill.version,
    author: skill.author,
    toolCount: skill.tools.length,
    metadata: skill.metadata,
  }));

  const response: ApiResponse = {
    success: true,
    data: allSkills,
    timestamp: new Date().toISOString(),
  };

  return c.json(response);
});

/**
 * GET /api/skills/active
 * 
 * List all active skills
 */
skillsRoutes.get('/active', (c) => {
  const activeSkills = skillsManager.getActiveSkills().map(skill => ({
    id: skill.id,
    name: skill.name,
    description: skill.description,
    category: skill.category,
  }));

  const response: ApiResponse = {
    success: true,
    data: activeSkills,
    timestamp: new Date().toISOString(),
  };

  return c.json(response);
});

/**
 * GET /api/skills/statistics
 * 
 * Get skills statistics
 */
skillsRoutes.get('/statistics', (c) => {
  const stats = skillsManager.getStatistics();

  const response: ApiResponse = {
    success: true,
    data: stats,
    timestamp: new Date().toISOString(),
  };

  return c.json(response);
});

/**
 * GET /api/skills/:id
 * 
 * Get skill details
 */
skillsRoutes.get('/:id', (c) => {
  const skillId = c.req.param('id');

  const skill = skillsManager.getSkill(skillId);

  if (!skill) {
    const response: ApiResponse = {
      success: false,
      error: {
        code: 'SKILL_NOT_FOUND',
        message: `Skill ${skillId} not found`,
      },
      timestamp: new Date().toISOString(),
    };

    return c.json(response, 404);
  }

  const response: ApiResponse = {
    success: true,
    data: {
      ...skill,
      tools: skill.tools.map(tool => ({
        name: tool.name,
        description: tool.description,
      })),
    },
    timestamp: new Date().toISOString(),
  };

  return c.json(response);
});

/**
 * POST /api/skills/:id/activate
 * 
 * Activate a skill
 */
skillsRoutes.post('/:id/activate', (c) => {
  const skillId = c.req.param('id');

  const success = skillsManager.activateSkill(skillId);

  if (!success) {
    const response: ApiResponse = {
      success: false,
      error: {
        code: 'SKILL_NOT_FOUND',
        message: `Skill ${skillId} not found`,
      },
      timestamp: new Date().toISOString(),
    };

    return c.json(response, 404);
  }

  logger.info('Skill activated', { skillId });

  const response: ApiResponse = {
    success: true,
    data: { skillId, activated: true },
    timestamp: new Date().toISOString(),
  };

  return c.json(response);
});

/**
 * POST /api/skills/:id/deactivate
 * 
 * Deactivate a skill
 */
skillsRoutes.post('/:id/deactivate', (c) => {
  const skillId = c.req.param('id');

  const success = skillsManager.deactivateSkill(skillId);

  if (!success) {
    const response: ApiResponse = {
      success: false,
      error: {
        code: 'SKILL_NOT_ACTIVE',
        message: `Skill ${skillId} is not active`,
      },
      timestamp: new Date().toISOString(),
    };

    return c.json(response, 404);
  }

  logger.info('Skill deactivated', { skillId });

  const response: ApiResponse = {
    success: true,
    data: { skillId, deactivated: true },
    timestamp: new Date().toISOString(),
  };

  return c.json(response);
});

/**
 * GET /api/skills/category/:category
 * 
 * Get skills by category
 */
skillsRoutes.get('/category/:category', (c) => {
  const category = c.req.param('category') as any;

  const skills = skillsManager.getSkillsByCategory(category).map(skill => ({
    id: skill.id,
    name: skill.name,
    description: skill.description,
    version: skill.version,
  }));

  const response: ApiResponse = {
    success: true,
    data: skills,
    timestamp: new Date().toISOString(),
  };

  return c.json(response);
});

/**
 * GET /api/skills/search
 * 
 * Search skills by query
 */
skillsRoutes.get('/search', async (c) => {
  const query = c.req.query('q');

  if (!query) {
    const response: ApiResponse = {
      success: false,
      error: {
        code: 'INVALID_REQUEST',
        message: 'Missing query parameter: q',
      },
      timestamp: new Date().toISOString(),
    };

    return c.json(response, 400);
  }

  const skills = skillsManager.searchSkills(query).map(skill => ({
    id: skill.id,
    name: skill.name,
    description: skill.description,
    category: skill.category,
  }));

  const response: ApiResponse = {
    success: true,
    data: skills,
    timestamp: new Date().toISOString(),
  };

  return c.json(response);
});

/**
 * POST /api/skills/import
 * 
 * Import a skill from JSON configuration
 */
skillsRoutes.post('/import', async (c) => {
  try {
    const body = await c.req.json();
    const { config } = body;

    if (!config) {
      const response: ApiResponse = {
        success: false,
        error: {
          code: 'INVALID_REQUEST',
          message: 'Missing required field: config',
        },
        timestamp: new Date().toISOString(),
      };

      return c.json(response, 400);
    }

    const success = skillsManager.importSkill(JSON.stringify(config));

    if (!success) {
      const response: ApiResponse = {
        success: false,
        error: {
          code: 'IMPORT_FAILED',
          message: 'Failed to import skill',
        },
        timestamp: new Date().toISOString(),
      };

      return c.json(response, 500);
    }

    const response: ApiResponse = {
      success: true,
      data: { imported: true },
      timestamp: new Date().toISOString(),
    };

    return c.json(response);
  } catch (error) {
    logger.error('Failed to import skill', error);

    const response: ApiResponse = {
      success: false,
      error: {
        code: 'IMPORT_ERROR',
        message: error instanceof Error ? error.message : 'Unknown error',
      },
      timestamp: new Date().toISOString(),
    };

    return c.json(response, 500);
  }
});

/**
 * GET /api/skills/:id/export
 * 
 * Export a skill as JSON configuration
 */
skillsRoutes.get('/:id/export', (c) => {
  const skillId = c.req.param('id');

  const config = skillsManager.exportSkill(skillId);

  if (!config) {
    const response: ApiResponse = {
      success: false,
      error: {
        code: 'SKILL_NOT_FOUND',
        message: `Skill ${skillId} not found`,
      },
      timestamp: new Date().toISOString(),
    };

    return c.json(response, 404);
  }

  const response: ApiResponse = {
    success: true,
    data: { config: JSON.parse(config) },
    timestamp: new Date().toISOString(),
  };

  return c.json(response);
});

